/**
 * Created by jimmy on 2017/6/8.
 */

var logger = require("../lib/log").logger;
var userService = require("../service/UserService");
var async = require("async");
var wechat = require("../lib/wechat");


exports.wxauth = function (req,res,next) {
    var code = req.query.code;
    var state = req.query.state;
    var stateMap = {'index':'/home/index','login':'/usr/login'};
    var userin;

    if(!code){
        logger.error('微信认证失败');
        res.status(200).end('微信认证失败');
        return;
    }

    async.waterfall([
        function (callback) {
            wechat.authCode(code,'1',callback);
        },
        function (res,callback) {
            logger.debug("ret:"+res)
            if(!res || !res.openid){
                logger.error('微信认证失败: wx authcode 失败');
                callback(200,null)
            }
            var openid = res.openid;
            var accessToken = res.access_token;
            req.session.openid = openid;
            wechat.getUserInfo(accessToken, openid,callback);
        },
        function (userinfo,callback) {
            if(!userinfo){
                logger.error('微信认证失败: 获取userinfo失败');
                callback(200,null);
            }

            req.session.nickname = userinfo.nickname;
            req.session.head_img = userinfo.headimgurl;
            logger.debug(JSON.stringify(req.session));
            userin = userinfo;
            callback(null,userinfo);
        },
        function (users,callback) {
            if (!users) {
                logger.error('微信认证失败: 获取userinfo失败');
                callback(200, null);
            }
            userService.getBaseUser(users.openid, callback);
        },
        function (user,callback) {
        console.log(user);
            if(user.length == 0){
                var data = {open_id:userin.openid,nick_name:userin.nickname,head_img:userin.headimgurl,sex:userin.sex};
                userService.insWxUser(data,function (err,result) {
                    if(!err){
                        userService.insUser(data,callback);
                    }
                });

            }else {
                logger.debug(JSON.stringify(user[0]));
                // req.session.nickname = userin.nickname;
                // req.session.openid = userin.openid;
                // req.session.head_img = userin.headimgurl;
                req.session.sex = userin.sex;
                req.session.userid = user[0].buser_id;
                req.session.mobile = user[0].mobile;
                req.session.birthday = user[0].birthday;
                req.session.realName = user[0].real_name;
                req.session.level = user[0].level;
                req.session.discount = user[0].discount;
                callback(null,{code:0,msg:'OK'});
            }

        }
    ],function (err,result) {
        logger.debug("err:"+err+"============result:",result);
        if(err){
            logger.error(err);
            res.status(200).end('微信认证失败');
        }else {
            res.redirect(stateMap[state]);
        }
    });
};
